/**轻松游戏 */
const router = require('koa-router')();
const DB = require('../db');

/**添加游戏最高分
 * @param {number} score 分数
 */
router.post('/addBestScore', async (ctx, next) => {
  const userName = ctx.request.header.username;
  if (!userName) {
    ctx.body = {
      code: '0008',
      message: '请先登录',
      data: {}
    }
    return;
  }
  const { score } = ctx.request.body;
  if (!score && score !== 0) {
    ctx.body = {
      code: '0002',
      message: '缺少必要参数',
      data: {}
    }
    return;
  }
  const r = await DB.find('users', { userName });
  if (!r || r.length === 0) {
    ctx.body = {
      code: '0013',
      message: '未找到指定用户',
      data: ''
    }
    return;
  }
  const addObj = {
    time: Date.now(),
    best: score
  }
  const { avatarUrl, uid } = r[0];
  const obj = { userName, avatarUrl, uid, flappyBird: addObj };
  const r0 = await DB.find('games', { userName });
  if (!r0 || r0.length === 0) {
    await DB.add('games', obj);
  } else {
    if (score > r0[0].flappyBird.best) {
      await DB.updateValue('games', { userName }, { flappyBird: addObj });
    }
  }
  ctx.body = {
    code: '0000',
    message: 'ok',
    data: addObj
  }
})

/**获取游戏最高分 */
router.get('/getBirdBest', async (ctx, next) => {
  const userName = ctx.request.header.username;
  if (!userName) {
    ctx.body = {
      code: '0008',
      message: '请先登录',
      data: {}
    }
    return;
  }
  const r0 = await DB.find('games', { userName });
  if (!r0 || r0.length === 0) {
    const r1 = await DB.find('users', { userName });
    if (!r1 || r1.length === 0) {
      ctx.body = {
        code: '0008',
        message: '未找到指定用户',
        data: {}
      }
      return;
    }
    ctx.body = {
      code: '0000',
      message: '获取成功',
      data: {
        avatarUrl: r1[0].avatarUrl,
        best: 0
      }
    }
  } else {
    ctx.body = {
      code: '0000',
      message: '获取成功',
      data: {
        avatarUrl: r0[0].avatarUrl,
        best: r0[0].flappyBird.best
      }
    }
  }
})

/**获取得分榜单 */
router.get('/gamesRank', async (ctx, next) => {
  const r0 = await DB.findInSortAndLimit('games', { $match: { 'flappyBird.best': { $gt: 0 } } }, { 'flappyBird.best': -1 }, 100);
  ctx.body = {
    code: '0000',
    message: 'ok',
    data: r0
  }
})

module.exports = router;